package net.wicp.tams.common.apiext.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;

import lombok.extern.slf4j.Slf4j;
import net.wicp.tams.common.Conf;
import net.wicp.tams.common.apiext.SshAssist;
import net.wicp.tams.common.apiext.StringUtil;
import net.wicp.tams.common.constant.dic.YesOrNo;

/***
 * jdbc工具类，纯jdbc没有连接池
 * 
 * @author zhoujunhui
 *
 */
@Slf4j
public abstract class JdbcConnection {

	public static Connection getConnection(String driverName, String dburl, String userName, String pwd) {
		Connection conn = null;
		try {
			Class.forName(driverName);
			if (StringUtil.isNull(userName) || StringUtil.isNull(pwd)) {
				conn = DriverManager.getConnection(dburl);
			} else {
				conn = DriverManager.getConnection(dburl, userName, pwd);
			}
			return conn;
		} catch (Exception e) {
			log.error(String.format("连接错误，地址[%s]", dburl), e);
		}
		return null;
	}

	public static Connection getConnection(String driverName, String dburl) {
		return getConnection(driverName, dburl, null, null);
	}

	public static Connection getConnectionMyql(String dburl) {
		return getConnection("com.mysql.jdbc.Driver", dburl);
	}

	public static Connection getConnectionMyql(String dburl, String userName, String pwd) {
		return getConnection("com.mysql.jdbc.Driver", dburl, userName, pwd);
	}

	public static Connection getConnectionMyql(String ip, int port, String user, String pwd, YesOrNo isSsh) {
		String url;
		if (isSsh != null && isSsh == YesOrNo.yes) {
			SshAssist.ssh(Integer.parseInt(Conf.get("common.apiext.ssh.proxy.localhost.port")), ip, port);
			url = String.format("jdbc:mysql://%s:%s?autoReconnect=true&useUnicode=true&characterEncoding=utf-8",
					"localhost", Conf.get("common.apiext.ssh.proxy.localhost.port"));
		} else {
			url = String.format("jdbc:mysql://%s:%s?autoReconnect=true&useUnicode=true&characterEncoding=utf-8", ip,
					port);
		}
		java.sql.Connection conn = JdbcConnection.getConnectionMyql(url, user, pwd);
		return conn;
	}

}
